{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "2161d9b5",
   "metadata": {},
   "source": [
    "# Handling handlers\n",
    "\n",
    "> How handlers work in FastHTML"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "c4859e91",
   "metadata": {},
   "outputs": [],
   "source": [
    "from fasthtml.common import *\n",
    "from collections import namedtuple\n",
    "from typing import TypedDict\n",
    "from datetime import datetime\n",
    "import json,time"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "cab9ef0b",
   "metadata": {},
   "outputs": [],
   "source": [
    "app = FastHTML()"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "262184ee",
   "metadata": {},
   "source": [
    "The `FastHTML` class is the main application class for FastHTML apps."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "f912bfa6",
   "metadata": {},
   "outputs": [],
   "source": [
    "rt = app.route"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "cee03009",
   "metadata": {},
   "source": [
    "`app.route` is used to register route handlers. It is a decorator, which means we place it before a function that is used as a handler. Because it's used frequently in most FastHTML applications, we often alias it as `rt`, as we do here."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "f5ce3a89",
   "metadata": {},
   "source": [
    "## Basic Route Handling"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "313af67b",
   "metadata": {},
   "outputs": [],
   "source": [
    "@rt(\"/hi\")\n",
    "def get(): return 'Hi there'"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "d049d94d",
   "metadata": {},
   "source": [
    "Handler functions can return strings directly. These strings are sent as the response body to the client."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "82287e75",
   "metadata": {},
   "outputs": [],
   "source": [
    "cli = Client(app)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "b1dd47e3",
   "metadata": {},
   "source": [
    "`Client` is a test client for FastHTML applications. It allows you to simulate requests to your app without running a server."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "5e0e207d",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "'Hi there'"
      ]
     },
     "execution_count": null,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "cli.get('/hi').text"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "42c18142",
   "metadata": {},
   "source": [
    "The `get` method on a `Client` instance simulates GET requests to the app. It returns a response object that has a `.text` attribute, which you can use to access the body of the response. It calls `httpx.get` internally -- all httpx HTTP verbs are supported."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "1763888b",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "'Postal'"
      ]
     },
     "execution_count": null,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "@rt(\"/hi\")\n",
    "def post(): return 'Postal'\n",
    "cli.post('/hi').text"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "6792f8a0",
   "metadata": {},
   "source": [
    "Handler functions can be defined for different HTTP methods on the same route. Here, we define a `post` handler for the `/hi` route. The `Client` instance can simulate different HTTP methods, including POST requests."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "65b673bf",
   "metadata": {},
   "source": [
    "## Request and Response Objects"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "274666db",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "'testserver'"
      ]
     },
     "execution_count": null,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "@app.get(\"/hostie\")\n",
    "def show_host(req): return req.headers['host']\n",
    "cli.get('/hostie').text"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "d38dfe7a",
   "metadata": {},
   "source": [
    "Handler functions can accept a `req` (or `request`) parameter, which represents the incoming request. This object contains information about the request, including headers. In this example, we return the `host` header from the request. The test client uses 'testserver' as the default host.\n",
    "\n",
    "In this example, we use `@app.get(\"/hostie\")` instead of `@rt(\"/hostie\")`. The `@app.get()` decorator explicitly specifies the HTTP method (GET) for the route, while `@rt()` by default handles both GET and POST requests."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "36292bf3",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "'a yoyo'"
      ]
     },
     "execution_count": null,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "@rt\n",
    "def yoyo(): return 'a yoyo'\n",
    "cli.post('/yoyo').text"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "08162086",
   "metadata": {},
   "source": [
    "If the `@rt` decorator is used without arguments, it uses the function name as the route path. Here, the `yoyo` function becomes the handler for the `/yoyo` route. This handler responds to GET and POST methods, since a specific method wasn't provided."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "0d813cd0",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      " <!doctype html>\n",
      " <html>\n",
      "   <div>Text.</div>\n",
      " </html>\n",
      "\n"
     ]
    }
   ],
   "source": [
    "@rt\n",
    "def ft1(): return Html(Div('Text.'))\n",
    "print(cli.get('/ft1').text)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "42d62408",
   "metadata": {},
   "source": [
    "Handler functions can return [`FT`](https://www.fastht.ml/docs/explains/explaining_xt_components.html) objects, which are automatically converted to HTML strings. The `FT` class can take other `FT` components as arguments, such as `Div`. This allows for easy composition of HTML elements in your responses."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "43f20c45",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      " <!doctype html>\n",
      " <html>\n",
      "   <div hx-post=\"/yoyo\">Text.</div>\n",
      " </html>\n",
      "\n"
     ]
    }
   ],
   "source": [
    "@app.get\n",
    "def autopost(): return Html(Div('Text.', hx_post=yoyo.to()))\n",
    "print(cli.get('/autopost').text)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "bfbaa72c",
   "metadata": {},
   "source": [
    "The `rt` decorator modifies the `yoyo` function by adding a `to()` method. This method returns the route path associated with the handler. It's a convenient way to reference the route of a handler function dynamically.\n",
    "\n",
    "In the example, `yoyo.to()` is used as the value for `hx_post`. This means when the div is clicked, it will trigger an HTMX POST request to the route of the `yoyo` handler. This approach allows for flexible, DRY code by avoiding hardcoded route strings and automatically updating if the route changes.\n",
    "\n",
    "This pattern is particularly useful in larger applications where routes might change, or when building reusable components that need to reference their own routes dynamically."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "1aac05b2",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      " <!doctype html>\n",
      " <html>\n",
      "   <body>\n",
      "     <div hx-post=\"/hostie?a=b\" class=\"px-2\">Text.</div>\n",
      "   </body>\n",
      " </html>\n",
      "\n"
     ]
    }
   ],
   "source": [
    "@app.get\n",
    "def autoget(): return Html(Body(Div('Text.', cls='px-2', hx_post=show_host.to(a='b'))))\n",
    "print(cli.get('/autoget').text)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "a3ed70bb",
   "metadata": {},
   "source": [
    "The `rt()` method of handler functions can also accept parameters. When called with parameters, it returns the route path with a query string appended. In this example, `show_host.to(a='b')` generates the path `/hostie?a=b`.\n",
    "\n",
    "The `Body` component is used here to demonstrate nesting of FT components. `Div` is nested inside `Body`, showcasing how you can create more complex HTML structures.\n",
    "\n",
    "The `cls` parameter is used to add a CSS class to the `Div`. This translates to the `class` attribute in the rendered HTML. (`class` can't be used as a parameter name directly in Python since it's a reserved word.)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "87cb61fd",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      " <!doctype html>\n",
      " <html>\n",
      "   <head>\n",
      "     <title>Foo</title>\n",
      "     <meta charset=\"utf-8\">\n",
      "     <meta name=\"viewport\" content=\"width=device-width, initial-scale=1, viewport-fit=cover\">\n",
      "<script src=\"https://unpkg.com/htmx.org@2.0.4/dist/htmx.min.js\"></script><script src=\"https://cdn.jsdelivr.net/gh/answerdotai/fasthtml-js@1.0.12/fasthtml.js\"></script><script src=\"https://cdn.jsdelivr.net/gh/answerdotai/surreal@main/surreal.js\"></script><script src=\"https://cdn.jsdelivr.net/gh/gnat/css-scope-inline@main/script.js\"></script><script>\n",
      "    function sendmsg() {\n",
      "        window.parent.postMessage({height: document.documentElement.offsetHeight}, '*');\n",
      "    }\n",
      "    window.onload = function() {\n",
      "        sendmsg();\n",
      "        document.body.addEventListener('htmx:afterSettle',    sendmsg);\n",
      "        document.body.addEventListener('htmx:wsAfterMessage', sendmsg);\n",
      "    };</script>   </head>\n",
      "   <body>\n",
      "     <h1>bar</h1>\n",
      "   </body>\n",
      " </html>\n",
      "\n"
     ]
    }
   ],
   "source": [
    "@rt('/ft2')\n",
    "def get(): return Title('Foo'),H1('bar')\n",
    "print(cli.get('/ft2').text)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "1fbded86",
   "metadata": {},
   "source": [
    "Handler functions can return multiple `FT` objects as a tuple. The first item is treated as the `Title`, and the rest are added to the `Body`. When the request is not an HTMX request, FastHTML automatically adds necessary HTML boilerplate, including default `head` content with required scripts.\n",
    "\n",
    "When using `app.route` (or `rt`), if the function name matches an HTTP verb (e.g., `get`, `post`, `put`, `delete`), that HTTP method is automatically used for the route. In this case, a path must be explicitly provided as an argument to the decorator."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "108d93d3",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      " <title>Foo</title>\n",
      " <h1>bar</h1>\n",
      "\n"
     ]
    }
   ],
   "source": [
    "hxhdr = {'headers':{'hx-request':\"1\"}}\n",
    "print(cli.get('/ft2', **hxhdr).text)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "11c03809",
   "metadata": {},
   "source": [
    "For HTMX requests (indicated by the `hx-request` header), FastHTML returns only the specified components without the full HTML structure. This allows for efficient partial page updates in HTMX applications."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "42b8d631",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      " <h1>bar</h1>\n",
      "\n"
     ]
    }
   ],
   "source": [
    "@rt('/ft3')\n",
    "def get(): return H1('bar')\n",
    "print(cli.get('/ft3', **hxhdr).text)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "afe0ad04",
   "metadata": {},
   "source": [
    "When a handler function returns a single `FT` object for an HTMX request, it's rendered as a single HTML partial."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "b9e4eb09",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      " <!doctype html>\n",
      " <html>\n",
      "   <head>\n",
      "     <title>hi</title>\n",
      "   </head>\n",
      "   <body>\n",
      "     <p>there</p>\n",
      "   </body>\n",
      " </html>\n",
      "\n"
     ]
    }
   ],
   "source": [
    "@rt('/ft4')\n",
    "def get(): return Html(Head(Title('hi')), Body(P('there')))\n",
    "\n",
    "print(cli.get('/ft4').text)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "09946692",
   "metadata": {},
   "source": [
    "Handler functions can return a complete `Html` structure, including `Head` and `Body` components. When a full HTML structure is returned, FastHTML doesn't add any additional boilerplate. This gives you full control over the HTML output when needed."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "00725561",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "welcome!\n"
     ]
    }
   ],
   "source": [
    "@rt\n",
    "def index(): return \"welcome!\"\n",
    "print(cli.get('/').text)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "2f8d151b",
   "metadata": {},
   "source": [
    "The `index` function is a special handler in FastHTML. When defined without arguments to the `@rt` decorator, it automatically becomes the handler for the root path (`'/'`). This is a convenient way to define the main page or entry point of your application."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "7657a637",
   "metadata": {},
   "source": [
    "## Path and Query Parameters"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "64343367",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "'Good day to you, Alexis!'"
      ]
     },
     "execution_count": null,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "@rt('/user/{nm}', name='gday')\n",
    "def get(nm:str=''): return f\"Good day to you, {nm}!\"\n",
    "cli.get('/user/Alexis').text"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "d1d598ee",
   "metadata": {},
   "source": [
    "Handler functions can use path parameters, defined using curly braces in the route -- this is implemented by Starlette directly, so all Starlette path parameters can be used. These parameters are passed as arguments to the function.\n",
    "\n",
    "The `name` parameter in the decorator allows you to give the route a name, which can be used for URL generation.\n",
    "\n",
    "In this example, `{nm}` in the route becomes the `nm` parameter in the function. The function uses this parameter to create a personalized greeting."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "29a96715",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      " <!doctype html>\n",
      " <html>\n",
      "   <div href=\"/user/Alexis\">Text.</div>\n",
      " </html>\n",
      "\n"
     ]
    }
   ],
   "source": [
    "@app.get\n",
    "def autolink(): return Html(Div('Text.', link=uri('gday', nm='Alexis')))\n",
    "print(cli.get('/autolink').text)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "203bc294",
   "metadata": {},
   "source": [
    "The `uri` function is used to generate URLs for named routes. It takes the route name as its first argument, followed by any path or query parameters needed for that route.\n",
    "\n",
    "In this example, `uri('gday', nm='Alexis')` generates the URL for the route named 'gday' (which we defined earlier as '/user/{nm}'), with 'Alexis' as the value for the 'nm' parameter.\n",
    "\n",
    "The `link` parameter in FT components sets the `href` attribute of the rendered HTML element. By using `uri()`, we can dynamically generate correct URLs even if the underlying route structure changes.\n",
    "\n",
    "FastHTML provides several shorthand attributes that enable URL resolution: `link`= (becomes `href`=), `get`= (becomes `hx-get`=), `post`= (becomes `hx-post`=), `put`=, `delete`=, and `patch`=. These shorthands are required for `uri()` resolution to work at render time.\n",
    "\n",
    "Important: Using `hx_get=uri(...)` directly will not resolve the URL - you must use the shorthand `get=uri(...)` instead.\n",
    "\n",
    "This approach promotes maintainable code by centralizing route definitions and avoiding hardcoded URLs throughout the application."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "54266599",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "'http://testserver/user/Alexis; http://testserver/hostie'"
      ]
     },
     "execution_count": null,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "@rt('/link')\n",
    "def get(req): return f\"{req.url_for('gday', nm='Alexis')}; {req.url_for('show_host')}\"\n",
    "\n",
    "cli.get('/link').text"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "fbcf796d",
   "metadata": {},
   "source": [
    "The `url_for` method of the request object can be used to generate URLs for named routes. It takes the route name as its first argument, followed by any path parameters needed for that route.\n",
    "\n",
    "In this example, `req.url_for('gday', nm='Alexis')` generates the full URL for the route named 'gday', including the scheme and host. Similarly, `req.url_for('show_host')` generates the URL for the 'show_host' route.\n",
    "\n",
    "This method is particularly useful when you need to generate absolute URLs, such as for email links or API responses. It ensures that the correct host and scheme are included, even if the application is accessed through different domains or protocols."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "48d73da1",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "'/user/Jeremy'"
      ]
     },
     "execution_count": null,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "app.url_path_for('gday', nm='Jeremy')"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c8105d19",
   "metadata": {},
   "source": [
    "The `url_path_for` method of the application can be used to generate URL paths for named routes. Unlike `url_for`, it returns only the path component of the URL, without the scheme or host.\n",
    "\n",
    "In this example, `app.url_path_for('gday', nm='Jeremy')` generates the path '/user/Jeremy' for the route named 'gday'.\n",
    "\n",
    "This method is useful when you need relative URLs or just the path component, such as for internal links or when constructing URLs in a host-agnostic manner."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "381a1b68",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "<Response [200 OK]>\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "/Users/iflath/git/AnswerDotAI/fasthtml/build/__editable__.python_fasthtml-0.12.1-py3-none-any/fasthtml/core.py:188: UserWarning: `nope has no type annotation and is not a recognised special name, so is ignored.\n",
      "  if arg!='resp': warn(f\"`{arg} has no type annotation and is not a recognised special name, so is ignored.\")\n"
     ]
    },
    {
     "data": {
      "text/plain": [
       "''"
      ]
     },
     "execution_count": null,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "@rt('/oops')\n",
    "def get(nope): return nope\n",
    "r = cli.get('/oops?nope=1')\n",
    "print(r)\n",
    "r.text"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "129f78c6",
   "metadata": {},
   "source": [
    "Handler functions can include parameters, but they must be type-annotated or have special names (like `req`) to be recognized. In this example, the `nope` parameter is not annotated, so it's ignored, resulting in a warning.\n",
    "\n",
    "When a parameter is ignored, it doesn't receive the value from the query string. This can lead to unexpected behavior, as the function attempts to return `nope`, which is undefined.\n",
    "\n",
    "The `cli.get('/oops?nope=1')` call succeeds with a 200 OK status because the handler doesn't raise an exception, but it returns an empty response, rather than the intended value.\n",
    "\n",
    "To fix this, you should either add a type annotation to the parameter (e.g., `def get(nope: str):`) or use a recognized special name like `req`."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "9e983268",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      " <body>\n",
      "   <h4>Next is 2.</h4>\n",
      " </body>\n",
      "\n"
     ]
    }
   ],
   "source": [
    "@rt('/html/{idx}')\n",
    "def get(idx:int): return Body(H4(f'Next is {idx+1}.'))\n",
    "print(cli.get('/html/1', **hxhdr).text)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "5eb395ec",
   "metadata": {},
   "source": [
    "Path parameters can be type-annotated, and FastHTML will automatically convert them to the specified type if possible. In this example, `idx` is annotated as `int`, so it's converted from the string in the URL to an integer."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "bb085687",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Getting jph.ico from /foo/\n"
     ]
    }
   ],
   "source": [
    "reg_re_param(\"imgext\", \"ico|gif|jpg|jpeg|webm\")\n",
    "\n",
    "@rt(r'/static/{path:path}{fn}.{ext:imgext}')\n",
    "def get(fn:str, path:str, ext:str): return f\"Getting {fn}.{ext} from /{path}\"\n",
    "\n",
    "print(cli.get('/static/foo/jph.ico').text)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "2fb982bf",
   "metadata": {},
   "source": [
    "The `reg_re_param` function is used to register custom path parameter types using regular expressions. Here, we define a new path parameter type called \"imgext\" that matches common image file extensions.\n",
    "\n",
    "Handler functions can use complex path patterns with multiple parameters and custom types. In this example, the route pattern `r'/static/{path:path}{fn}.{ext:imgext}'` uses three path parameters:\n",
    "\n",
    "1. `path`: A Starlette built-in type that matches any path segments\n",
    "2. `fn`: The filename without extension\n",
    "3. `ext`: Our custom \"imgext\" type that matches specific image extensions"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "c2cbb818",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "alexnet\n"
     ]
    }
   ],
   "source": [
    "ModelName = str_enum('ModelName', \"alexnet\", \"resnet\", \"lenet\")\n",
    "\n",
    "@rt(\"/models/{nm}\")\n",
    "def get(nm:ModelName): return nm\n",
    "\n",
    "print(cli.get('/models/alexnet').text)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "e0783625",
   "metadata": {},
   "source": [
    "We define `ModelName` as an enum with three possible values: \"alexnet\", \"resnet\", and \"lenet\". Handler functions can use these enum types as parameter annotations. In this example, the `nm` parameter is annotated with `ModelName`, which ensures that only valid model names are accepted.\n",
    "\n",
    "When a request is made with a valid model name, the handler function returns that name. This pattern is useful for creating type-safe APIs with a predefined set of valid values."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "747fc88c",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "foo.txt\n"
     ]
    }
   ],
   "source": [
    "@rt(\"/files/{path}\")\n",
    "async def get(path: Path): return path.with_suffix('.txt')\n",
    "print(cli.get('/files/foo').text)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "55793433",
   "metadata": {},
   "source": [
    "Handler functions can use `Path` objects as parameter types. The `Path` type is from Python's standard library `pathlib` module, which provides an object-oriented interface for working with file paths. In this example, the `path` parameter is annotated with `Path`, so FastHTML automatically converts the string from the URL to a `Path` object.\n",
    "\n",
    "This approach is particularly useful when working with file-related routes, as it provides a convenient and platform-independent way to handle file paths."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "ab7dbef3",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "{\"name\":\"Bar\"}\n"
     ]
    }
   ],
   "source": [
    "fake_db = [{\"name\": \"Foo\"}, {\"name\": \"Bar\"}]\n",
    "\n",
    "@rt(\"/items/\")\n",
    "def get(idx:int|None = 0): return fake_db[idx]\n",
    "print(cli.get('/items/?idx=1').text)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "cebc22b7",
   "metadata": {},
   "source": [
    "Handler functions can use query parameters, which are automatically parsed from the URL. In this example, `idx` is a query parameter with a default value of 0. It's annotated as `int|None`, allowing it to be either an integer or None.\n",
    "\n",
    "The function uses this parameter to index into a fake database (`fake_db`). When a request is made with a valid `idx` query parameter, the handler returns the corresponding item from the database."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "3fcd79dd",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "{\"name\":\"Foo\"}\n"
     ]
    }
   ],
   "source": [
    "print(cli.get('/items/').text)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "71ca4e0e",
   "metadata": {},
   "source": [
    "When no `idx` query parameter is provided, the handler function uses the default value of 0. This results in returning the first item from the `fake_db` list, which is `{\"name\":\"Foo\"}`.\n",
    "\n",
    "This behavior demonstrates how default values for query parameters work in FastHTML. They allow the API to have a sensible default behavior when optional parameters are not provided."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "bd37ec72",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "<Response [404 Not Found]>\n"
     ]
    }
   ],
   "source": [
    "print(cli.get('/items/?idx=g'))"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "57101dea",
   "metadata": {},
   "source": [
    "When an invalid value is provided for a typed query parameter, FastHTML returns a 404 Not Found response. In this example, 'g' is not a valid integer for the `idx` parameter, so the request fails with a 404 status.\n",
    "\n",
    "This behavior ensures type safety and prevents invalid inputs from reaching the handler function."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "7eb43107",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Coming\n",
      "Not coming\n"
     ]
    }
   ],
   "source": [
    "@app.get(\"/booly/\")\n",
    "def _(coming:bool=True): return 'Coming' if coming else 'Not coming'\n",
    "print(cli.get('/booly/?coming=true').text)\n",
    "print(cli.get('/booly/?coming=no').text)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "cd03f359",
   "metadata": {},
   "source": [
    "Handler functions can use boolean query parameters. In this example, `coming` is a boolean parameter with a default value of `True`. FastHTML automatically converts string values like 'true', 'false', '1', '0', 'on', 'off', 'yes', and 'no' to their corresponding boolean values.\n",
    "\n",
    "The underscore `_` is used as the function name in this example to indicate that the function's name is not important or won't be referenced elsewhere. This is a common Python convention for throwaway or unused variables, and it works here because FastHTML uses the route decorator parameter, when provided, to determine the URL path, not the function name. By default, both `get` and `post` methods can be used in routes that don't specify an http method (by either using `app.get`, `def get`, or the `methods` parameter to `app.route`)."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "2356f7ab",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "2024-05-17 14:00:00\n"
     ]
    }
   ],
   "source": [
    "@app.get(\"/datie/\")\n",
    "def _(d:parsed_date): return d\n",
    "date_str = \"17th of May, 2024, 2p\"\n",
    "print(cli.get(f'/datie/?d={date_str}').text)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "8bc0da51",
   "metadata": {},
   "source": [
    "Handler functions can use `date` objects as parameter types. FastHTML uses `dateutil.parser` library to automatically parse a wide variety of date string formats into `date` objects."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "aaeed51d",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "FastHTML\n"
     ]
    }
   ],
   "source": [
    "@app.get(\"/ua\")\n",
    "async def _(user_agent:str): return user_agent\n",
    "print(cli.get('/ua', headers={'User-Agent':'FastHTML'}).text)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "ec48fe7c",
   "metadata": {},
   "source": [
    "Handler functions can access HTTP headers by using parameter names that match the header names. In this example, `user_agent` is used as a parameter name, which automatically captures the value of the 'User-Agent' header from the request.\n",
    "\n",
    "The `Client` instance allows setting custom headers for test requests. Here, we set the 'User-Agent' header to 'FastHTML' in the test request."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "ed42ed51",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "1\n",
      "1\n"
     ]
    }
   ],
   "source": [
    "@app.get(\"/hxtest\")\n",
    "def _(htmx): return htmx.request\n",
    "print(cli.get('/hxtest', headers={'HX-Request':'1'}).text)\n",
    "\n",
    "@app.get(\"/hxtest2\")\n",
    "def _(foo:HtmxHeaders, req): return foo.request\n",
    "print(cli.get('/hxtest2', headers={'HX-Request':'1'}).text)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "d0c9cc55",
   "metadata": {},
   "source": [
    "Handler functions can access HTMX-specific headers using either the special `htmx` parameter name, or a parameter annotated with `HtmxHeaders`. Both approaches provide access to HTMX-related information.\n",
    "\n",
    "In these examples, the `htmx.request` attribute returns the value of the 'HX-Request' header."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "4efd072f",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "foo\n"
     ]
    }
   ],
   "source": [
    "app.chk = 'foo'\n",
    "@app.get(\"/app\")\n",
    "def _(app): return app.chk\n",
    "print(cli.get('/app').text)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "94f50286",
   "metadata": {},
   "source": [
    "Handler functions can access the `FastHTML` application instance using the special `app` parameter name. This allows handlers to access application-level attributes and methods.\n",
    "\n",
    "In this example, we set a custom attribute `chk` on the application instance. The handler function then uses the `app` parameter to access this attribute and return its value."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "856a2b93",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "foo\n",
      "Headers({'mykey': 'myval', 'content-length': '3', 'content-type': 'text/html; charset=utf-8'})\n"
     ]
    }
   ],
   "source": [
    "@app.get(\"/app2\")\n",
    "def _(foo:FastHTML): return foo.chk,HttpHeader(\"mykey\", \"myval\")\n",
    "r = cli.get('/app2', **hxhdr)\n",
    "print(r.text)\n",
    "print(r.headers)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "85cfd244",
   "metadata": {},
   "source": [
    "Handler functions can access the `FastHTML` application instance using a parameter annotated with `FastHTML`. This allows handlers to access application-level attributes and methods, just like using the special `app` parameter name.\n",
    "\n",
    "Handlers can return tuples containing both content and `HttpHeader` objects. `HttpHeader` allows setting custom HTTP headers in the response.\n",
    "\n",
    "In this example:\n",
    "\n",
    "- We define a handler that returns both the `chk` attribute from the application and a custom header.\n",
    "- The `HttpHeader(\"mykey\", \"myval\")` sets a custom header in the response.\n",
    "- We use the test client to make a request and examine both the response text and headers.\n",
    "- The response includes the custom header \"mykey\" along with standard headers like content-length and content-type."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "1591dde8",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Headers({'hx-location': 'http://example.org', 'content-length': '0', 'content-type': 'text/html; charset=utf-8'})\n"
     ]
    }
   ],
   "source": [
    "@app.get(\"/app3\")\n",
    "def _(foo:FastHTML): return HtmxResponseHeaders(location=\"http://example.org\")\n",
    "r = cli.get('/app3')\n",
    "print(r.headers)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "1bf8de32",
   "metadata": {},
   "source": [
    "Handler functions can return `HtmxResponseHeaders` objects to set HTMX-specific response headers. This is useful for HTMX-specific behaviors like client-side redirects.\n",
    "\n",
    "In this example we define a handler that returns an `HtmxResponseHeaders` object with a `location` parameter, which sets the `HX-Location` header in the response. HTMX uses this for client-side redirects."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "b8be4ef3",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "<Response [303 See Other]>"
      ]
     },
     "execution_count": null,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "@app.get(\"/app4\")\n",
    "def _(foo:FastHTML): return Redirect(\"http://example.org\")\n",
    "cli.get('/app4', follow_redirects=False)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "971ac23c",
   "metadata": {},
   "source": [
    "Handler functions can return `Redirect` objects to perform HTTP redirects. This is useful for redirecting users to different pages or external URLs.\n",
    "\n",
    "In this example:\n",
    "\n",
    "- We define a handler that returns a `Redirect` object with the URL \"http://example.org\".\n",
    "- The `cli.get('/app4', follow_redirects=False)` call simulates a GET request to the '/app4' route without following redirects.\n",
    "- The response has a 303 See Other status code, indicating a redirect.\n",
    "\n",
    "The `follow_redirects=False` parameter is used to prevent the test client from automatically following the redirect, allowing us to inspect the redirect response itself."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "e713a48a",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "<function fasthtml.core.Redirect.__response__(self, req)>"
      ]
     },
     "execution_count": null,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "Redirect.__response__"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "9923102b",
   "metadata": {},
   "source": [
    "The `Redirect` class in FastHTML implements a `__response__` method, which is a special method recognized by the framework. When a handler returns a `Redirect` object, FastHTML internally calls this `__response__` method to replace the original response.\n",
    "\n",
    "The `__response__` method takes a `req` parameter, which represents the incoming request. This allows the method to access request information if needed when constructing the redirect response."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "8a91b0af",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      " <!doctype html>\n",
      " <html>\n",
      "   <head>\n",
      "     <title>hi</title>\n",
      "     <meta property=\"image\">\n",
      "     <meta property=\"site_name\">\n",
      "     <meta charset=\"utf-8\">\n",
      "     <meta name=\"viewport\" content=\"width=device-width, initial-scale=1, viewport-fit=cover\">\n",
      "<script src=\"https://unpkg.com/htmx.org@2.0.4/dist/htmx.min.js\"></script><script src=\"https://cdn.jsdelivr.net/gh/answerdotai/fasthtml-js@1.0.12/fasthtml.js\"></script><script src=\"https://cdn.jsdelivr.net/gh/answerdotai/surreal@main/surreal.js\"></script><script src=\"https://cdn.jsdelivr.net/gh/gnat/css-scope-inline@main/script.js\"></script><script>\n",
      "    function sendmsg() {\n",
      "        window.parent.postMessage({height: document.documentElement.offsetHeight}, '*');\n",
      "    }\n",
      "    window.onload = function() {\n",
      "        sendmsg();\n",
      "        document.body.addEventListener('htmx:afterSettle',    sendmsg);\n",
      "        document.body.addEventListener('htmx:wsAfterMessage', sendmsg);\n",
      "    };</script>   </head>\n",
      "   <body>\n",
      "     <h1>hi</h1>\n",
      "   </body>\n",
      " </html>\n",
      "\n"
     ]
    }
   ],
   "source": [
    "@rt\n",
    "def meta(): \n",
    "    return ((Title('hi'),H1('hi')),\n",
    "        (Meta(property='image'), Meta(property='site_name')))\n",
    "\n",
    "print(cli.post('/meta').text)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "6c27edcb",
   "metadata": {},
   "source": [
    "FastHTML automatically identifies elements typically placed in the `<head>` (like `Title` and `Meta`) and positions them accordingly, while other elements go in the `<body>`.\n",
    "\n",
    "In this example:\n",
    "- `(Title('hi'), H1('hi'))` defines the title and main heading. The title is placed in the head, and the H1 in the body.\n",
    "- `(Meta(property='image'), Meta(property='site_name'))` defines two meta tags, which are both placed in the head."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "403fcae3",
   "metadata": {},
   "source": [
    "## APIRouter"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "f8138c07",
   "metadata": {},
   "source": [
    "`APIRouter` is useful when you want to split your application routes across multiple `.py` files that are part of a single FastHTMl application. It accepts an optional `prefix` argument that will be applied to all routes within that instance of `APIRouter`.\n",
    "\n",
    "Below we define several hypothetical product related routes in a `products.py` and then demonstrate how they can seamlessly be incorporated into a FastHTML app instance."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "5988523d",
   "metadata": {},
   "outputs": [],
   "source": [
    "# products.py\n",
    "ar = APIRouter(prefix=\"/products\")\n",
    "\n",
    "@ar(\"/all\")\n",
    "def all_products(req):\n",
    "    return Div(\n",
    "        \"Welcome to the Products Page! Click the button below to look at the details for product 42\",\n",
    "        Div(\n",
    "            Button(\n",
    "                \"Details\",\n",
    "                hx_get=req.url_for(\"details\", pid=42),\n",
    "                hx_target=\"#products_list\",\n",
    "                hx_swap=\"outerHTML\",\n",
    "            ),\n",
    "        ),\n",
    "        id=\"products_list\",\n",
    "    )\n",
    "\n",
    "\n",
    "@ar.get(\"/{pid}\", name=\"details\")\n",
    "def details(pid: int):\n",
    "    return f\"Here are the product details for ID: {pid}\""
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c7b2325a",
   "metadata": {},
   "source": [
    "Since we specified the `prefix=/products` in our hypothetical `products.py` file, all routes defined in that file will be found under `/products`."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "001ff0b8",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "/products/all\n",
      "/products/{pid}\n"
     ]
    }
   ],
   "source": [
    "print(str(ar.rt_funcs.all_products))\n",
    "print(str(ar.rt_funcs.details))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "49795185",
   "metadata": {},
   "outputs": [],
   "source": [
    "# main.py\n",
    "# from products import ar\n",
    "\n",
    "app, rt = fast_app()\n",
    "ar.to_app(app)\n",
    "\n",
    "@rt\n",
    "def index():\n",
    "    return Div(\n",
    "        \"Click me for a look at our products\",\n",
    "        hx_get=ar.rt_funcs.all_products,\n",
    "        hx_swap=\"outerHTML\",\n",
    "    )"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "7eb1a33f",
   "metadata": {},
   "source": [
    "Note how you can reference our python route functions via `APIRouter.rt_funcs` in your `hx_{http_method}` calls like normal."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "311ca66a",
   "metadata": {},
   "source": [
    "## Form Data and JSON Handling"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "9a20c15d",
   "metadata": {},
   "outputs": [],
   "source": [
    "app = FastHTML()\n",
    "rt = app.route\n",
    "cli = Client(app)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "aa343fc7",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Alexis\n"
     ]
    }
   ],
   "source": [
    "@app.post('/profile/me')\n",
    "def profile_update(username: str): return username\n",
    "\n",
    "r = cli.post('/profile/me', data={'username' : 'Alexis'}).text\n",
    "assert r == 'Alexis'\n",
    "print(r)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "34baa57d",
   "metadata": {},
   "source": [
    "Handler functions can accept form data parameters, without needing to manually extract it from the request. In this example, `username` is expected to be sent as form data.\n",
    "\n",
    "The `data` parameter in the `cli.post()` method simulates sending form data in the request.\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "a3596991",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Missing required field: username\n"
     ]
    },
    {
     "data": {
      "text/plain": [
       "<Response [400 Bad Request]>"
      ]
     },
     "execution_count": null,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "r = cli.post('/profile/me', data={})\n",
    "assert r.status_code == 400\n",
    "print(r.text)\n",
    "r"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "02c778a5",
   "metadata": {},
   "source": [
    "If required form data is missing, FastHTML automatically returns a 400 Bad Request response with an error message."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "fdb9239c",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "'unknown name'"
      ]
     },
     "execution_count": null,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "@app.post('/pet/dog')\n",
    "def pet_dog(dogname: str = None): return dogname or 'unknown name'\n",
    "r = cli.post('/pet/dog', data={}).text\n",
    "r"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "1241f926",
   "metadata": {},
   "outputs": [],
   "source": [
    "#| hide\n",
    "assert r == 'unknown name'"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "031807b2",
   "metadata": {},
   "source": [
    "Handlers can have optional form data parameters with default values. In this example, `dogname` is an optional parameter with a default value of `None`.\n",
    "\n",
    "Here, if the form data doesn't include the `dogname` field, the function uses the default value. The function returns either the provided `dogname` or 'unknown name' if `dogname` is `None`."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "2045fc36",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "{\"a\":1,\"b\":\"foo\",\"nm\":\"me\"}\n"
     ]
    }
   ],
   "source": [
    "@dataclass\n",
    "class Bodie: a:int;b:str\n",
    "\n",
    "@rt(\"/bodie/{nm}\")\n",
    "def post(nm:str, data:Bodie):\n",
    "    res = asdict(data)\n",
    "    res['nm'] = nm\n",
    "    return res\n",
    "\n",
    "print(cli.post('/bodie/me', data=dict(a=1, b='foo', nm='me')).text)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "cb20aa7d",
   "metadata": {},
   "source": [
    "You can use dataclasses to define structured form data. In this example, `Bodie` is a dataclass with `a` (int) and `b` (str) fields.\n",
    "\n",
    "FastHTML automatically converts the incoming form data to a `Bodie` instance where attribute names match parameter names. Other form data elements are matched with parameters with the same names (in this case, `nm`).\n",
    "\n",
    "Handler functions can return dictionaries, which FastHTML automatically JSON-encodes."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "3cf710c5",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "{\"a\":\"1\",\"b\":\"foo\"}\n"
     ]
    }
   ],
   "source": [
    "@app.post(\"/bodied/\")\n",
    "def bodied(data:dict): return data\n",
    "\n",
    "d = dict(a=1, b='foo')\n",
    "print(cli.post('/bodied/', data=d).text)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "1464cedd",
   "metadata": {},
   "source": [
    "`dict` parameters capture all form data as a dictionary. In this example, the `data` parameter is annotated with `dict`, so FastHTML automatically converts all incoming form data into a dictionary.\n",
    "\n",
    "Note that when form data is converted to a dictionary, all values become strings, even if they were originally numbers. This is why the 'a' key in the response has a string value \"1\" instead of the integer 1."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "be68e29e",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "{\"a\":\"1\",\"b\":\"foo\"}\n"
     ]
    }
   ],
   "source": [
    "nt = namedtuple('Bodient', ['a','b'])\n",
    "\n",
    "@app.post(\"/bodient/\")\n",
    "def bodient(data:nt): return asdict(data)\n",
    "print(cli.post('/bodient/', data=d).text)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "fec9a661",
   "metadata": {},
   "source": [
    "Handler functions can use named tuples to define structured form data. In this example, `Bodient` is a named tuple with `a` and `b` fields.\n",
    "\n",
    "FastHTML automatically converts the incoming form data to a `Bodient` instance where field names match parameter names. As with the previous example, all form data values are converted to strings in the process."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "381b2ecf",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "{\"a\":1,\"b\":\"foo\"}\n"
     ]
    }
   ],
   "source": [
    "class BodieTD(TypedDict): a:int;b:str='foo'\n",
    "\n",
    "@app.post(\"/bodietd/\")\n",
    "def bodient(data:BodieTD): return data\n",
    "print(cli.post('/bodietd/', data=d).text)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "f5410c5a",
   "metadata": {},
   "source": [
    "You can use `TypedDict` to define structured form data with type hints. In this example, `BodieTD` is a `TypedDict` with `a` (int) and `b` (str) fields, where `b` has a default value of 'foo'.\n",
    "\n",
    "FastHTML automatically converts the incoming form data to a `BodieTD` instance where keys match the defined fields. Unlike with regular dictionaries or named tuples, FastHTML respects the type hints in `TypedDict`, converting values to the specified types when possible (e.g., converting '1' to the integer 1 for the 'a' field)."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "3366d88f",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "a: 1; b: foo\n"
     ]
    }
   ],
   "source": [
    "class Bodie2:\n",
    "    a:int|None; b:str\n",
    "    def __init__(self, a, b='foo'): store_attr()\n",
    "\n",
    "@app.post(\"/bodie2/\")\n",
    "def bodie(d:Bodie2): return f\"a: {d.a}; b: {d.b}\"\n",
    "print(cli.post('/bodie2/', data={'a':1}).text)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "fa908fef",
   "metadata": {},
   "source": [
    "Custom classes can be used to define structured form data. Here, `Bodie2` is a custom class with `a` (int|None) and `b` (str) attributes, where `b` has a default value of 'foo'. The `store_attr()` function (from fastcore) automatically assigns constructor parameters to instance attributes.\n",
    "\n",
    "FastHTML automatically converts the incoming form data to a `Bodie2` instance, matching form fields to constructor parameters. It respects type hints and default values."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "6c1fbc4b",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      " <title>It worked!</title>\n",
      "<main class=\"container\">   <h1>It worked!</h1>\n",
      "   <p>15, Lorem</p>\n",
      "</main>\n"
     ]
    }
   ],
   "source": [
    "@app.post(\"/b\")\n",
    "def index(it: Bodie): return Titled(\"It worked!\", P(f\"{it.a}, {it.b}\"))\n",
    "\n",
    "s = json.dumps({\"b\": \"Lorem\", \"a\": 15})\n",
    "print(cli.post('/b', headers={\"Content-Type\": \"application/json\", 'hx-request':\"1\"}, data=s).text)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "2e6074a7",
   "metadata": {},
   "source": [
    "Handler functions can accept JSON data as input, which is automatically parsed into the specified type. In this example, `it` is of type `Bodie`, and FastHTML converts the incoming JSON data to a `Bodie` instance.\n",
    "\n",
    "The `Titled` component is used to create a page with a title and main content. It automatically generates an `<h1>` with the provided title, wraps the content in a `<main>` tag with a \"container\" class, and adds a `title` to the head.\n",
    "\n",
    "When making a request with JSON data:\n",
    "- Set the \"Content-Type\" header to \"application/json\"\n",
    "- Provide the JSON data as a string in the `data` parameter of the request"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "ec0553e9",
   "metadata": {},
   "source": [
    "## Cookies, Sessions, File Uploads, and more"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "0c7b420e",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "\n"
     ]
    },
    {
     "data": {
      "text/plain": [
       "'Cookie was set at time 16:19:27.811570'"
      ]
     },
     "execution_count": null,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "@rt(\"/setcookie\")\n",
    "def get(): return cookie('now', datetime.now())\n",
    "\n",
    "@rt(\"/getcookie\")\n",
    "def get(now:parsed_date): return f'Cookie was set at time {now.time()}'\n",
    "\n",
    "print(cli.get('/setcookie').text)\n",
    "time.sleep(0.01)\n",
    "cli.get('/getcookie').text"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "3941ef8c",
   "metadata": {},
   "source": [
    "Handler functions can set and retrieve cookies. In this example:\n",
    "\n",
    "- The `/setcookie` route sets a cookie named 'now' with the current datetime.\n",
    "- The `/getcookie` route retrieves the 'now' cookie and returns its value.\n",
    "\n",
    "The `cookie()` function is used to create a cookie response. FastHTML automatically converts the datetime object to a string when setting the cookie, and parses it back to a date object when retrieving it."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "cd6d793b",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "HttpHeader(k='set-cookie', v='now=\"2025-01-30 16:19:29.997374\"; Path=/; SameSite=lax')"
      ]
     },
     "execution_count": null,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "cookie('now', datetime.now())"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "59c8e470",
   "metadata": {},
   "source": [
    "The `cookie()` function returns an `HttpHeader` object with the 'set-cookie' key. You can return it in a tuple along with `FT` elements, along with anything else FastHTML supports in responses."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "b8c0f5bc",
   "metadata": {},
   "outputs": [],
   "source": [
    "app = FastHTML(secret_key='soopersecret')\n",
    "cli = Client(app)\n",
    "rt = app.route"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "5bce33f0",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Set to 2025-01-30 16:19:31.078650\n"
     ]
    },
    {
     "data": {
      "text/plain": [
       "'Session time: 2025-01-30 16:19:31.078650'"
      ]
     },
     "execution_count": null,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "@rt(\"/setsess\")\n",
    "def get(sess, foo:str=''):\n",
    "    now = datetime.now()\n",
    "    sess['auth'] = str(now)\n",
    "    return f'Set to {now}'\n",
    "\n",
    "@rt(\"/getsess\")\n",
    "def get(sess): return f'Session time: {sess[\"auth\"]}'\n",
    "\n",
    "print(cli.get('/setsess').text)\n",
    "time.sleep(0.01)\n",
    "\n",
    "cli.get('/getsess').text"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "8eeac927",
   "metadata": {},
   "outputs": [],
   "source": [
    "#| hide\n",
    "assert cli.get('/getsess').status_code==200"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "9643b417",
   "metadata": {},
   "source": [
    "Sessions store and retrieve data across requests. To use sessions, you should to initialize the FastHTML application with a `secret_key`. This is used to cryptographically sign the cookie used by the session.\n",
    "\n",
    "The `sess` parameter in handler functions provides access to the session data. You can set and get session variables using dictionary-style access."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "4d17ab9c",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "# Release notes\n"
     ]
    }
   ],
   "source": [
    "@rt(\"/upload\")\n",
    "async def post(uf:UploadFile): return (await uf.read()).decode()\n",
    "\n",
    "with open('../../CHANGELOG.md', 'rb') as f:\n",
    "    print(cli.post('/upload', files={'uf':f}, data={'msg':'Hello'}).text[:15])"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "9e3f034e",
   "metadata": {},
   "source": [
    "Handler functions can accept file uploads using Starlette's `UploadFile` type. In this example:\n",
    "\n",
    "- The `/upload` route accepts a file upload named `uf`.\n",
    "- The `UploadFile` object provides an asynchronous `read()` method to access the file contents.\n",
    "- We use `await` to read the file content asynchronously and decode it to a string.\n",
    "\n",
    "We added `async` to the handler function because it uses `await` to read the file content asynchronously. In Python, any function that uses `await` must be declared as `async`. This allows the function to be run asynchronously, potentially improving performance by not blocking other operations while waiting for the file to be read."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "46b2e24f",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "# FastHTML\n"
     ]
    }
   ],
   "source": [
    "app.static_route('.md', static_path='../..')\n",
    "print(cli.get('/README.md').text[:10])"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "d3529d25",
   "metadata": {},
   "outputs": [],
   "source": [
    "#| hide\n",
    "assert cli.get('/README.md').text[:10] == '# FastHTML'"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "f738cd30",
   "metadata": {},
   "source": [
    "The `static_route` method of the FastHTML application allows serving static files with specified extensions from a given directory. In this example:\n",
    "\n",
    "- `.md` files are served from the `../..` directory (two levels up from the current directory).\n",
    "- Accessing `/README.md` returns the contents of the README.md file from that directory."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "68b95489",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Help on method static_route_exts in module fasthtml.core:\n",
      "\n",
      "static_route_exts(prefix='/', static_path='.', exts='static') method of fasthtml.core.FastHTML instance\n",
      "    Add a static route at URL path `prefix` with files from `static_path` and `exts` defined by `reg_re_param()`\n",
      "\n"
     ]
    }
   ],
   "source": [
    "help(app.static_route_exts)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "0ed44d28",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "404 Not Found\n"
     ]
    }
   ],
   "source": [
    "app.static_route_exts()\n",
    "assert cli.get('/README.txt').status_code == 404\n",
    "print(cli.get('/README.txt').text[:50])"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "8728ffc6",
   "metadata": {},
   "source": [
    "The `static_route_exts` method of the FastHTML application allows serving static files with specified extensions from a given directory. By default:\n",
    "\n",
    "- It serves files from the current directory ('.').\n",
    "- It uses the 'static' regex, which includes common static file extensions like 'ico', 'gif', 'jpg', 'css', 'js', etc.\n",
    "- The URL prefix is set to '/'.\n",
    "\n",
    "The 'static' regex is defined by FastHTML using this code:\n",
    "\n",
    "```python\n",
    "reg_re_param(\"static\", \"ico|gif|jpg|jpeg|webm|css|js|woff|png|svg|mp4|webp|ttf|otf|eot|woff2|txt|html|map\")\n",
    "```"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "102c17ab",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Headers({'access-control-allow-origin': '*', 'access-control-allow-methods': 'POST', 'access-control-allow-headers': '*', 'content-length': '0', 'set-cookie': 'session_=eyJhdXRoIjogIjIwMjUtMDEtMzAgMTY6MTk6MzEuMDc4NjUwIn0=.Z5vtZA.1ooY2RCWopWAbLYDy6660g_LlHI; path=/; Max-Age=31536000; httponly; samesite=lax'})\n"
     ]
    }
   ],
   "source": [
    "@rt(\"/form-submit/{list_id}\")\n",
    "def options(list_id: str):\n",
    "    headers = {\n",
    "        'Access-Control-Allow-Origin': '*',\n",
    "        'Access-Control-Allow-Methods': 'POST',\n",
    "        'Access-Control-Allow-Headers': '*',\n",
    "    }\n",
    "    return Response(status_code=200, headers=headers)\n",
    "\n",
    "print(cli.options('/form-submit/2').headers)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "0c9c25de",
   "metadata": {},
   "source": [
    "FastHTML handlers can handle OPTIONS requests and set custom headers. In this example:\n",
    "\n",
    "- The `/form-submit/{list_id}` route handles OPTIONS requests.\n",
    "- Custom headers are set to allow cross-origin requests (CORS).\n",
    "- The function returns a Starlette `Response` object with a 200 status code and the custom headers.\n",
    "\n",
    "You can return any Starlette Response type from a handler function, giving you full control over the response when needed."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "42a5810a",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      " <!doctype html>\n",
      " <html>\n",
      "   <head>\n",
      "     <title>FastHTML page</title>\n",
      "     <meta charset=\"utf-8\">\n",
      "     <meta name=\"viewport\" content=\"width=device-width, initial-scale=1, viewport-fit=cover\">\n",
      "<script src=\"https://unpkg.com/htmx.org@2.0.4/dist/htmx.min.js\"></script><script src=\"https://cdn.jsdelivr.net/gh/answerdotai/fasthtml-js@1.0.12/fasthtml.js\"></script><script src=\"https://cdn.jsdelivr.net/gh/answerdotai/surreal@main/surreal.js\"></script><script src=\"https://cdn.jsdelivr.net/gh/gnat/css-scope-inline@main/script.js\"></script><script>\n",
      "    function sendmsg() {\n",
      "        window.parent.postMessage({height: document.documentElement.offsetHeight}, '*');\n",
      "    }\n",
      "    window.onload = function() {\n",
      "        sendmsg();\n",
      "        document.body.addEventListener('htmx:afterSettle',    sendmsg);\n",
      "        document.body.addEventListener('htmx:wsAfterMessage', sendmsg);\n",
      "    };</script>   </head>\n",
      "   <body>\n",
      "     <div>nope</div>\n",
      "   </body>\n",
      " </html>\n",
      "\n"
     ]
    }
   ],
   "source": [
    "def _not_found(req, exc): return Div('nope')\n",
    "\n",
    "app = FastHTML(exception_handlers={404:_not_found})\n",
    "cli = Client(app)\n",
    "rt = app.route\n",
    "\n",
    "r = cli.get('/')\n",
    "print(r.text)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "ef936900",
   "metadata": {},
   "source": [
    "FastHTML allows you to define custom exception handlers -- in this case, a custom 404 (Not Found) handler function `_not_found`, which returns a `Div` component with the text 'nope'."
   ]
  }
 ],
 "metadata": {},
 "nbformat": 4,
 "nbformat_minor": 5
}
